
#import "FQDFeedBaseViewController.h"
#import "FQDRevealRefreshHeader.h"
#import "FQDRefreshFooter.h"
#import "FQDFeedCollectionViewCell.h"
#import "FQDFeedCellItemProvider.h"
#import "FQDFeedCellItem.h"
#import "FQDFeed.h"

#import "SDWebImageManager.h"
#import "UICollectionView+XYTemplateLayoutCell.h"
#import "UICollectionView+XYIndexPathSizeCache.h"

@interface FQDFeedBaseViewController () 

// 信息流CollectionView
@property (nonatomic, strong, readwrite) UICollectionView *feedCollectionView;
// 顶部下拉刷新页眉
@property (nonatomic, strong) FQDRevealRefreshHeader *refreshHeader;
// 底部上拉刷新页脚
@property (nonatomic, strong) FQDRefreshFooter *refreshFooter;

@end

@implementation FQDFeedBaseViewController

#pragma mark View life cycle

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    // 好奇心日报大图比较多，设置图片缓存大小限制，防止图片缓存占用内存过大
    [[SDImageCache sharedImageCache] setMaxCacheSize:30*1024*1024];
    [[SDImageCache sharedImageCache] setMaxMemoryCost:30*1024*1024];
    [[SDImageCache sharedImageCache] setShouldDecompressImages:NO];
    [[SDWebImageDownloader sharedDownloader] setShouldDecompressImages:NO];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
    [[SDImageCache sharedImageCache] setMaxCacheSize:0];
    [[SDImageCache sharedImageCache] setMaxMemoryCost:0];
    [[SDImageCache sharedImageCache] setShouldDecompressImages:YES];
    [[SDWebImageDownloader sharedDownloader] setShouldDecompressImages:YES];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setupFeedCollectionView];
}

- (void)setupFeedCollectionView
{
    CGRect viewRect = self.view.bounds;
    self.feedContentView = [[UIView alloc] initWithFrame:viewRect];
    self.feedContentView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    [self.view addSubview:self.feedContentView];
    
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.minimumLineSpacing = 5.0f;
    flowLayout.minimumInteritemSpacing = 0;
    flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
    
    self.feedCollectionView = [[UICollectionView alloc] initWithFrame:viewRect
                                             collectionViewLayout:flowLayout];
    self.feedCollectionView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    self.feedCollectionView.backgroundColor = FQDFeedContainerBackgroundColor;
    self.feedCollectionView.delegate = self;
    self.feedCollectionView.dataSource = self;
    [self.feedContentView addSubview:self.feedCollectionView];
    
    NSArray *cellClasses = [self cellClasses];
    for (Class cellClass in cellClasses) {
        [self.feedCollectionView registerClass:cellClass
                    forCellWithReuseIdentifier:[cellClass reuseId]];
    }
    
    if (!self.disableRefreshHeader) {
        self.refreshHeader =
        [FQDRevealRefreshHeader headerWithTarget:self action:@selector(loadNewCellItems)];
        [self.feedCollectionView addSubview:self.refreshHeader];
        self.refreshHeader.layer.zPosition = -1;
    }
    
    self.refreshFooter = [FQDRefreshFooter footerWithRefreshingTarget:self
                                                     refreshingAction:@selector(loadMoreCellItems)];
    self.feedCollectionView.mj_footer = self.refreshFooter;
    
}

#pragma mark - Public methods
- (void)loadNewCellItems
{
    [self loadNewCellItemsWithCompletion:nil];
}

- (void)loadNewCellItemsWithCompletion:(void (^)(BOOL))completion
{
    WeakSelf;
    [self.provider loadNewCellItems:^(BOOL isSuccess) {
        [weakSelf.feedCollectionView xy_clearIndexPathSizeCache];
        [weakSelf.feedCollectionView reloadData];
        [weakSelf.refreshHeader endRefreshing];
        
        if (![self.provider hasMoreCellItems]) {
            [weakSelf.refreshFooter setHidden:YES];
        }
        
        completion ? completion(isSuccess) : nil;
    }];
}
- (void)loadMoreCellItems
{
    [self loadMoreCellItemsWithCompletion:nil];
}

- (void)loadMoreCellItemsWithCompletion:(void (^)(BOOL))completion
{
    WeakSelf;
    if ([self.provider hasMoreCellItems]) {
        [self.provider loadMoreCellItems:^(BOOL isSuccess) {
            [weakSelf.feedCollectionView reloadData];
            [weakSelf.refreshFooter endRefreshing];
            completion ? completion(isSuccess) : nil;
        }];
    } else {
        [weakSelf.refreshFooter endRefreshingWithNoMoreData];
        completion ? completion(YES) : nil ;
    }
}

- (void)reloadData
{
    [self.feedCollectionView reloadData];
}

- (NSArray *)cellClasses
{
    return @[];
}

#pragma mark - Regular Cell
- (Class)cellClassForCellItem:(FQDFeedCellItem *)cellItem
{
    return nil;
}

// 配置信息流单元格
- (void)configureFeedCell:(UICollectionViewCell *)feedCell atIndexPath:(NSIndexPath *)indexPath inCollectionView:(UICollectionView *)collectionView
{
    
}

- (void)didSelectCellItem:(FQDFeedCellItem *)cellItem atIndexPath:(NSIndexPath *)indexPath inCollectionView:(UICollectionView *)collectionView
{
    
}

#pragma mark - Header Cell
// 返回需要注册的HeaderCell类
- (Class)headerCellClassAtIndexPath:(NSIndexPath *)indexPath inCollectionView:(UICollectionView *)collectionView
{
    return nil;
}

- (NSInteger)numberOfHeaderCellsInCollectionView:(UICollectionView *)collectionView
{
    return 0;
}

- (void)configureHeaderCell:(UICollectionViewCell *)headerCell atIndexPath:(NSIndexPath *)indexPath inCollectionView:(UICollectionView *)collectionView
{
    
}

- (void)didSelectHeaderCellAtIndexPath:(NSIndexPath *)indexPath inCollectionView:(UICollectionView *)collectionView
{
    
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForHeaderCellAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeZero;
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetsForHeaderCellSection:(NSInteger)section
{
    return UIEdgeInsetsZero;
}

#pragma mark - UICollectionViewDelegateFlowLayout
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    UIEdgeInsets insets = UIEdgeInsetsZero;
    if ([self respondsToSelector:@selector(collectionView:layout:insetsForHeaderCellSection:)]) {
        insets = [self collectionView:collectionView layout:collectionViewLayout insetsForHeaderCellSection:section];
    }
    return insets;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    CGSize size = CGSizeMake(collectionView.frame.size.width, 100.0f);
    NSInteger headerCellCount = [self numberOfHeaderCellsInCollectionView:collectionView];
    if (indexPath.section < headerCellCount) {
        if ([self respondsToSelector:@selector(collectionView:layout:sizeForHeaderCellAtIndexPath:)]) {
            size = [self collectionView:collectionView layout:collectionViewLayout sizeForHeaderCellAtIndexPath:indexPath];
        }
    } else {
        NSInteger feedIndex = indexPath.item;
        FQDFeedCellItem *cellItem = self.provider.cellItems[feedIndex];
        Class feedCellClass = [self cellClassForCellItem:cellItem];
        CGFloat cvWidth = collectionView.frame.size.width;
        size = [collectionView xy_getCellSizeForCellClass:[feedCellClass class] width:cvWidth cacheByIndexPath:indexPath
                config:^(FQDFeedCollectionViewCell *cell) {
                    cell.cellItem = cellItem;
                }];
    }
    return size;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    NSInteger headerCellCount = [self numberOfHeaderCellsInCollectionView:collectionView];
    if (section == headerCellCount) {
        return 5.0f;
    }
    return 0;
}

#pragma mark - UICollectionViewDataSource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    NSInteger headerCellCount = [self numberOfHeaderCellsInCollectionView:collectionView];
    return 1 + headerCellCount;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    NSInteger headerCellCount = [self numberOfHeaderCellsInCollectionView:collectionView];
    if (section < headerCellCount) {
        return 1;
    } else {
        return [self.provider.cellItems count];
    }
    return 0;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    __block UICollectionViewCell *cell;
    
    // 修复下拉刷新Cell的subview会执行隐式动画的问题
    [CATransaction begin];
    [CATransaction setDisableActions:YES];
    
    NSInteger headerCellCount = [self numberOfHeaderCellsInCollectionView:collectionView];
    if (indexPath.section < headerCellCount) {
        Class headerCellClass = [self headerCellClassAtIndexPath:indexPath inCollectionView:collectionView];
        NSParameterAssert(headerCellClass != nil);
        
        UICollectionViewCell *headerCell =
        [collectionView dequeueReusableCellWithReuseIdentifier:[headerCellClass reuseId]
                                                  forIndexPath:indexPath];
        if ([self respondsToSelector:@selector(configureHeaderCell:atIndexPath:inCollectionView:)]) {
            [self configureHeaderCell:headerCell atIndexPath:indexPath inCollectionView:collectionView];
        }
        cell = headerCell;
    } else {
        NSInteger feedIndex = indexPath.item;
        FQDFeedCellItem *cellItem = self.provider.cellItems[feedIndex];
        Class feedCellClass = [self cellClassForCellItem:cellItem];
        FQDFeedCollectionViewCell *feedCell =
        [collectionView dequeueReusableCellWithReuseIdentifier:[feedCellClass reuseId]
                                                  forIndexPath:indexPath];
        feedCell.cellItem = cellItem;
        feedCell.delegate = self;
        feedCell.backgroundColor = [UIColor whiteColor];
        if ([self respondsToSelector:@selector(configureFeedCell:atIndexPath:inCollectionView:)]) {
            [self configureFeedCell:feedCell atIndexPath:indexPath inCollectionView:collectionView];
        }
        cell = feedCell;
    }
    
    cell ? [cell layoutIfNeeded] : nil;
    [CATransaction commit];
    
    return cell;
}

#pragma mark - UICollectionViewDelegate
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSInteger headerCellCount = [self numberOfHeaderCellsInCollectionView:collectionView];
    if (indexPath.section < headerCellCount) {
        if ([self respondsToSelector:@selector(didSelectHeaderCellAtIndexPath:inCollectionView:)]) {
            [self didSelectHeaderCellAtIndexPath:indexPath inCollectionView:collectionView];
        }
    } else {
        FQDFeedCellItem *cellItem = self.provider.cellItems[indexPath.item];
        if ([self respondsToSelector:@selector(didSelectCellItem:atIndexPath:inCollectionView:)]) {
            [self didSelectCellItem:cellItem atIndexPath:indexPath inCollectionView:collectionView];
        }
    }
}

@end